<template>
  <div style="padding: 20px;">
    <div class="topLocation">员工信息管理 / 员工管理</div>
    <div class="topTool">
      <div class="group">员工姓名：</div>
      <el-input v-model="searchName" placeholder="请输入员工姓名" style="margin-right: 50px;"></el-input>
      <div class="group">员工性别：</div>
      <el-select v-model="searchGender" placeholder="请选择员工性别" style="margin-right: 50px;">
        <el-option label="男" value="男"></el-option>
        <el-option label="女" value="女"></el-option>
        <el-option label="所有性别" value=""></el-option>
      </el-select>
      <div class="group">月薪：</div>
      <el-input v-model="searchSalary" placeholder="请输入员工月薪" style="margin-right: 50px;"></el-input>
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="success" :icon="Plus" @click="handleAdd">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelList" v-if="multipleSelection.length > 0">删除选中员工</el-button>
    </div>
    <el-table
        :data="employeeData"
        :header-cell-style="{ background: '#f6f9fa'}"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="account" label="账号"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="gender" label="性别"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="phonenumber" label="手机号码"></el-table-column>
      <el-table-column prop="salary" label="月薪"></el-table-column>
      <el-table-column prop="hireDate" label="入职日期" :formatter="formatDate"></el-table-column>
      <el-table-column prop="role" label="角色"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 添加员工的对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="账号">
          <el-input
              v-model="form.account"
              autocomplete="off"
              :disabled="dialogTitle === '编辑员工'" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age" type="number" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="form.phonenumber" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="月薪">
          <el-input v-model="form.salary" type="number" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="入职日期">
          <el-date-picker v-model="form.hireDate" type="date" placeholder="选择入职日期"/>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="form.role" :disabled="true" value="员工" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogOk">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus, Search } from "@element-plus/icons-vue";

const employeeData = ref([]); // 员工数据
const currentPage = ref(1); // 当前页数
const pageSize = ref(5); // 每页显示条数
const total = ref(0); // 总记录数
const searchName = ref(''); // 员工姓名搜索关键字
const searchGender = ref(''); // 员工性别搜索关键字
const searchSalary = ref(''); // 月薪搜索关键字

const formatDate = (row, column, cellValue, index) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1);
  const day = date.getDate();
  const pad = (num) => num < 10 ? '0' + num : num;
  return `${year}-${pad(month)}-${pad(day)}`;
};

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/employee/findByPage', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchName.value,
      gender: searchGender.value,
      salary: searchSalary.value
    }
  }).then(response => {
    employeeData.value = response.data.data.records;
    total.value = response.data.data.total;
  }).catch(error => {
    console.error(error);
  });
};

onMounted(() => {
  getData();
});

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
      `您确定要删除员工【${row.name}】的记录吗?`,
      '危险操作'
  ).then(() => {
    delEmployee(row.id);
    ElMessage({
      type: 'success',
      message: '删除成功!',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    });
  });
};

const delEmployee = (employeeId) => {
  axios.delete(`http://localhost:8080/employee/${employeeId}`)
      .then(() => {
        getData();
      })
      .catch((error) => {
        console.error(error);
      });
};

const handleSearch = () => {
  const params = {
    name: searchName.value || null,
    gender: searchGender.value === "" ? null : searchGender.value,
    salary: searchSalary.value ? searchSalary.value : undefined
  };

  axios.get('http://localhost:8080/employee/search', { params })
      .then(response => {
        employeeData.value = response.data.data;
      })
      .catch(error => {
        console.error(error);
        ElMessage.error('查询失败');
      });
};

const handleSortChange = (sortData) => {
  const { prop, order } = sortData;
  employeeData.value = employeeData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

let multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item => item.id);
};

const handleDelList = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的员工！');
    return;
  }
  ElMessageBox.confirm(
      "您确定要删除选中的员工？",
      '危险操作'
  ).then(() => {
    multipleSelection.value.forEach((id) => {
      delEmployee(id);
    });
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!'
    });
  });
};

const dialogFormVisible = ref(false);
const dialogTitle = ref('添加员工');
const form = ref({
  id: null,
  account: '',
  password: '',
  name: '',
  gender: '男',
  age: null,
  phonenumber: '',
  salary: null,
  hireDate: '',
  role: '员工' // 默认为员工角色
});

const handleAdd = () => {
  dialogTitle.value = '添加员工';
  form.value = { ...form.value, id: null, account: '', password: '', name: '', gender: '男', age: null, phonenumber: '', salary: null, hireDate: '', role: '员工' };
  dialogFormVisible.value = true;
};

const handleEdit = (row) => {
  dialogTitle.value = '编辑员工';
  form.value = { ...row, role: '员工' }; // 编辑时设置角色为“员工”
  dialogFormVisible.value = true;
};

const dialogOk = () => {
  // 表单验证，确保所有字段都有值
  if (!form.value.name || !form.value.account || !form.value.password || !form.value.age || !form.value.phonenumber || !form.value.salary || !form.value.hireDate) {
    ElMessage.error('所有字段都必须填写');
    return; // 阻止后续操作
  }

  // 如果是添加员工操作
  if (dialogTitle.value === '添加员工') {
    // 账号重复检查
    axios.post('http://localhost:8080/employee/checkAccount', { account: form.value.account })
        .then(response => {
          // 检查账号是否存在
          if (response.data.data.exists == true) {
            ElMessage.error('账号已存在，请选择其他账号');
            return; // 阻止继续执行
          }

          // 账号不存在，继续添加员工
          axios.post('http://localhost:8080/employee', form.value)
              .then(() => {
                dialogFormVisible.value = false; // 关闭弹窗
                getData(); // 刷新数据
                ElMessage.success('添加成功!'); // 提示成功
              })
              .catch((error) => {
                console.error(error);
                ElMessage.error('添加员工失败，请稍后再试');
              });
        })
        .catch((error) => {
          console.error(error);
          ElMessage.error('账号检查失败，请稍后再试');
        });
  } else { // 编辑员工
    axios.put(`http://localhost:8080/employee/${form.value.id}`, form.value)
        .then(() => {
          dialogFormVisible.value = false; // 关闭弹窗
          getData(); // 刷新数据
          ElMessage.success('编辑成功!'); // 提示成功
        })
        .catch((error) => {
          console.error(error);
          ElMessage.error('编辑失败，请稍后再试');
        });
  }
};

</script>

<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px;     /* 设置字体大小为 14px */
}
</style>
